const M=require("ming_node");
/**
 "dependencies": {
    "@serialport/parser-readline": "^10.3.0",
    "serialport": "^10.4.0"
  }
 */
const { SerialPort } = require('serialport')
/**
 https://www.jb51.net/article/230274.htm
 */
class MingSericalRunCode {


    static isNodeExecute =true;

    static messageEvent=(m)=>{return 0}

    constructor({com,brand,messageEvent,isNodeExecute}) {
        this.options={ path: com, baudRate: brand };
        this.sp = new SerialPort( this.options);
        console.log(`connect ${com} ${brand}`)
        MingSericalRunCode.messageEvent=messageEvent;
        MingSericalRunCode.isNodeExecute=isNodeExecute;
        this.parser = null;

        this.rtsPort=1;
    }

    install(app,args){

    }

    async usartSend(m){
        return new Promise((resolve => {
            this.sp.write(m);
            this.sp.drain(err => {
                if (err) resolve(-1);
                resolve(0);
            });
        }))

    }

    setRtsPort(v){
        this.rtsPort=v;
        if(v==1){
            v=false;
        }else {
            v=true;
        }
        this.sp.set({  rts:v})
    }

    init(){
        this.parser.on('data', async (v) => {
            MingSericalRunCode.messageEvent(v);
        });
    }

}

module.exports = MingSericalRunCode;